using Avalonia.BiliBili.Units;
using Avalonia.BiliBili.ViewModels;
using Avalonia.Controls;
using Avalonia.Extensions.Controls;
using Avalonia.Extensions.Event;
using Avalonia.Input;
using Bilibili.Common.Log;
using Bilibili.Model.Season;
using Bilibili.WebClient.Api;
using DynamicData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Avalonia.BiliBili.Windows
{
    public partial class IndexWindow : WindowBase
    {
        private SeasonClient Client { get; }
        public bool HasInit { get; set; } = false;
        private int PageIndex { get; set; } = 1;
        private IndexViewModel ViewModel { get; }
        public IndexWindow()
        {
            InitializeComponent();
            Client = new SeasonClient();
            ViewModel = new IndexViewModel();
        }
        protected override void AfterInitializeComponent()
        {
            this.DataContext = ViewModel;
            listView.ScrollEnd += ListView_ScrollEnd;
            listView.ItemClick += ListView_ItemClick;
            RunOnUiThread(async () =>
            {
                try
                {
                    var result = await Client.GetCondition(1);
                    if (result.Code == 0)
                    {
                        var array = result.Data.ToObject<Condition>();
                        ViewModel.Condition.AddRange(array.Filter);
                        ConditonsInit();
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Instance.LogError("InitData", ex);
                }
            });
        }
        private void ListView_ItemClick(object? sender, ViewRoutedEventArgs e)
        {
            try
            {
                if (e.ClickMouse == MouseButton.Left && e.ClickItem is GridViewItem item &&
                    item.Content is SeasonIndexResultItemModel model)
                    Navigater.OpenWindow<BanInfoWindow>(model.Season_Id);
            }
            catch { }
        }
        private void ListView_ScrollEnd(object? sender, Interactivity.RoutedEventArgs e)
        {
            PageIndex++;
            RunOnUiThread(LoadData);
        }
        private void ConditonsInit()
        {
            RunOnUiThread(async () =>
           {
               try
               {
                   while (true)
                   {
                       if (conditons.Children.Count > 0)
                       {
                           foreach (StackPanel control in conditons.Children.Cast<StackPanel>())
                           {
                               var box = control.FindControls<ComboBox>();
                               if (box != null && box.Count() > 0)
                                   box.FirstOrDefault().SelectedIndex = 0;
                           }
                           break;
                       }
                       await Task.Delay(80);
                   }
               }
               catch (Exception ex)
               {
                   LogManager.Instance.LogError("ConditonsInit", ex);
               }
               finally
               {
                   HasInit = true;
                   RunOnUiThread(LoadData);
               }
           });
        }
        private async Task LoadData()
        {
            try
            {
                var conditonsArray = ViewModel.Condition.Select(item => $"&{item.Field}={Uri.EscapeDataString(item.Values.ElementAt(item.Current).Keyword)}");
                var conditons = $"{string.Join("", conditonsArray)}&sort=0";
                var result = await Client.GetResult(conditons, PageIndex, 1);
                if (result.Code == 0)
                {
                    var array = result.Data["list"].ToObject<List<SeasonIndexResultItemModel>>();
                    ViewModel.SeasonList.AddRange(array);
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("LoadData", ex);
            }
        }
        private void OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (HasInit && sender is ComboBox combo && combo.DataContext is FilterInfo info)
                {
                    PageIndex = 1;
                    info.Current = combo.SelectedIndex;
                    RunOnUiThread(LoadData);
                }
            }
            catch { }
        }
    }
}